<!--
 * @Author: your name
 * @Date: 2020-05-15 09:43:02
 * @LastEditTime: 2020-06-15 16:55:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v1.0.0\components\kmlc-com\kmlc-form-upload-img\kmlc-form-upload-img.vue
 -->
<template>
    <view class="container">
        
        <tui-list-cell :hover="false" :arrow="false">
            <view class="tui-line-cell">
                <view class="tui-title">
                    <view class="uni-uploader">
                        <view class="uni-uploader-head">
                            <view v-if="label" class="uni-uploader-title">
                                <text v-show="emData_.rules&&emData_.rules[0]&&emData_.rules[0].required" class="isrequire">*</text>
                                <text>{{label}}(点击可预览选好的图片)</text>
                                </view>
                            <view class="uni-uploader-info">{{imageList.length}}/{{this.count}}</view>
                            <!-- #ifdef APP-PLUS || MP-WEIXIN  -->
                            <view @click="saveFileMultiple" class="tui-right" v-show="imageList && Array.isArray(imageList)&&imageList.length>0">
                                <uni-icons type="download" color="#8f8f94" size="25" />
                            </view>
                            <!-- #endif -->
                        </view>
                        <view  class="uni-uploader-body">
                            <view class="uni-uploader__files">
                                <block v-for="(image,index) in imageList" :key="index">
                                    <view class="uni-uploader__file">
                                        <image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
                                    </view>
                                </block>
                                <view v-show="readonly_?false:true &&imageList.length<count" class="uni-uploader__input-box">
                                    <view class="uni-uploader__input" @tap="chooseImage"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </tui-list-cell>
        <avatar class="my-avatar" @upload="_uploadImg"  quality="1" ref="avatar"></avatar>
        <tui-tips ref="toast" ></tui-tips>
    </view>
</template>

<script>
import permision from "@/common/framework/libs/permission.js";
import {uploadFileUrl} from "@/pages/customForm/interface"
import {http} from '@/common/framework';
import avatar from "@/components/other-com/yq-avatar/yq-avatar.vue";
var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
var sizeType = [
    ['compressed'],
    ['original'],
    ['compressed', 'original']
]
export default {
    components:{
			avatar
		},
    props:{
        label: {
      type: String
    },
    emData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default: () => {
        return {};
      }
    },
    rules: {
      type: Array,
      default: () => {
        return [];
      }
    },
    model: {
      type: String
    },
    keyStr: {
      type: String
    }
    },
    data() {
        return {
            title: 'choose/previewImage',
            imageList: [],
            sourceTypeIndex: 2,
            sourceType: ['拍照', '相册', '拍照或相册'],
            sizeTypeIndex: 2,
            sizeType: ['压缩', '原图', '压缩或原图'],
            countIndex: 8,
            count: 9,
            // count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            emData_:{},
            readonly_:false,
            progress:0,
            isCutting_:true,
            uploadPath:'',
        }
    },
    onUnload() {
        this.imageList = [],
            this.sourceTypeIndex = 2,
            this.sourceType = ['拍照', '相册', '拍照或相册'],
            this.sizeTypeIndex = 2,
            this.sizeType = ['压缩', '原图', '压缩或原图'],
            this.count = 9;
    },
    watch:{
        'emData.options.defaultValue':function(val){
        // console.log('watch data uploadimg:',val);
        this.imageList =val||[];
        },
        emData(val){
        this.initemData();
        }
    },
    created() {
        this.initEmdata();
    },
    methods: {
        initEmdata(){
            this.uploadPath = uploadFileUrl;
            if (this.emData && this.emData.key) {
                this.emData_ = this.emData;
                this.sourceTypeIndex = this.emData.options.sourceTypeIndex;
                this.sizeTypeIndex = this.emData.options.sizeTypeIndex;
                this.count = this.emData.options.limit;
                this.readonly_ = this.emData.options.readonly;
                this.isCutting_ = this.emData.options.isCutting;
                this.emData.options.defaultValue? this.imageList = this.emData.options.defaultValue:[];
                this.emData.options.action?this.uploadPath =this.emData.options.action:null;
                this.rules_ = this.emData.rules;
            } else {
                this.emData_["options"] = this.options;
                this.emData_["rules"] = this.rules;
                this.emData_["model"] = this.model;
                this.emData_["key"] = this.keyStr;
                this.sourceTypeIndex = this.options.sourceTypeIndex;
                this.sizeTypeIndex = this.options.sizeTypeIndex;
                this.count = this.options.limit;
                this.readonly_ = this.options.readonly;
                this.isCutting_ = this.options.isCutting;
                this.options.defaultValue? this.imageList = this.options.defaultValue:[];
                this.options.action?this.uploadPath =this.options.action:null;
               
            }
        },
       
        chooseImage: async function() {

            // #ifdef APP-PLUS
            // TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
            if (this.sourceTypeIndex !== 2) {
                let status = await this.checkPermission();
                if (status !== 1) {
                    return;
                }
            }
            // #endif

            if (this.imageList.length === this.count) {
                let isContinue = await this.isFullImg();
                console.log("是否继续?", isContinue);
                if (!isContinue) {
                    return;
                }
            }
            if(this.isCutting_){
                this.$refs.avatar.fChooseImg(0,{
                    selWidth: '500upx', selHeight: '500upx', 
                    expWidth: '500upx', expHeight: '500upx',
                    inner: false
                });
            }else{
            uni.chooseImage({
                sourceType: sourceType[this.sourceTypeIndex],
                sizeType: sizeType[this.sizeTypeIndex],
                count: this.count -this.imageList.length ,
                success: (res) => {
                    console.log(res);
                    this._uploadImg({path:res.tempFilePaths[0]});
                },
                fail: (err) => {
                    // #ifdef APP-PLUS
                    if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
                        this.checkPermission(err.code);
                    }
                    // #endif
                    // #ifdef MP
                    uni.getSetting({
                        success: (res) => {
                            let authStatus = false;
                            switch (this.sourceTypeIndex) {
                                case 0:
                                    authStatus = res.authSetting['scope.camera'];
                                    break;
                                case 1:
                                    authStatus = res.authSetting['scope.album'];
                                    break;
                                case 2:
                                    authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
                                    break;
                                default:
                                    break;
                            }
                            if (!authStatus) {
                                uni.showModal({
                                    title: '授权失败',
                                    content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
                                    success: (res) => {
                                        if (res.confirm) {
                                            uni.openSetting()
                                        }
                                    }
                                })
                            }
                        }
                    })
                    // #endif
                }
            })
            }
        },
        isFullImg: function() {
            return new Promise((res) => {
                uni.showModal({
                    content: `已经有${this.count}张图片了,是否清空现有图片？`,
                    success: (e) => {
                        if (e.confirm) {
                            this.imageList = [];
                            res(true);
                        } else {
                            res(false)
                        }
                    },
                    fail: () => {
                        res(false)
                    }
                })
            })
        },
        previewImage: function(e) {
            var current = e.target.dataset.src
            uni.previewImage({
                current: current,
                urls: this.imageList
            })
        },
        async checkPermission(code) {
            let type = code ? code - 1 : this.sourceTypeIndex;
            let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
                await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
                    'android.permission.READ_EXTERNAL_STORAGE');

            if (status === null || status === 1) {
                status = 1;
            } else {
                uni.showModal({
                    content: "没有开启权限",
                    confirmText: "设置",
                    success: function(res) {
                        if (res.confirm) {
                            permision.gotoAppSetting();
                        }
                    }
                })
            }

            return status;
        },
         //图片上存
           async _uploadImg(rsp){
               let _this = this;
               let path = rsp.path;
               uni.showLoading({
                    title: '上传中...'+_this.progress +'%'
                });
               let parpms = {
                   url:this.uploadPath,
                   file:path,
                   fileType: 'image',
                   name:'file',
                   data:{
                       file:path,
                       fileType:'image',
                   },
                   onSuccess:function(Res){
						Res =typeof Res=='string'?JSON.parse(Res):Res;
                        uni.hideLoading();
                       if(Res && Res.success){
                           !_this.imageList?_this.imageList=[]:null;
                          _this.imageList.push(Res.result.path);
                          _this.$emit("onChangeVal", _this.imageList);
                        }else{
                            uni.showToast({
                                icon:'none',
                                title:Res.message ||'保存失败~！',
                            })
                        }
                       
                   },
                   onFail:function(res){
                       uni.hideLoading();
                       uni.showToast({
                            icon:'none',
                            title:res.message ||'保存失败~！',
                       })
                   },
                   onProgressUpdate:function(res){
                        _this.progress = res.progress;
                   },
               };
               http.upload(parpms);
            
            },
    async saveFileMultiple(){
        let saveRes=[];
        if (this.imageList && Array.isArray(this.imageList) && this.imageList.length>0) {
            for (let index = 0; index < this.imageList.length; index++) {
                const element = this.imageList[index];
                let res =  await this.saveFile(element);
                 console.log('res:',res);
                saveRes.push(res);
            }
            let successRes =  saveRes.filter(item=>item.success);
            console.log('saveRes:',saveRes);
            let options = {
                msg: `保存完成，成功${successRes.length}张，失败${this.imageList.length - successRes.length}张`,
                duration:  2000,
                type: successRes&&successRes.length/this.imageList&&this.imageList.length>0.5?'green':'waring'
            };
            this.$refs.toast.showTips(options);
        }
    },
    async saveFile(path){
        return new Promise((resolve, reject)=>{
            uni.downloadFile({
                url: path,
                success: (res) => {
                    uni.saveFile({
                        tempFilePath: res.tempFilePath,
                        success: (res) => {
                            resolve({success:true})
                        },
                        fail: (err) => {
                            reject({success:false,error:err})
                        }
                    })
                }
            });
        })
        
    }
    },
  modal: {
    prop: "imageList",
    event: "onChangeVal"
  }
}
</script>
<style lang="scss">
     .isrequire{ color:#d41200;}
</style>

<style lang="scss">
.container{
.my-avatar{height:0;}
}
    .tui-right {
		margin-left: auto;
		font-size: 26upx;
		line-height: 1;
		color: #999;
    }
    .uni-uploader-body{
        width: 92vw;
    }
</style>